package fictional.GUI;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.WindowAdapter;
import java.net.MalformedURLException;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;

import fictional.Common.IBL;
import fictional.Common.MessageItem;
import fictional.Common.ShortCharacterItem;

/**
 * A popup which shows all the user's private messages and 
 * enables them to delete/reply to them.
 */
@SuppressWarnings("serial")
public class ViewPrivateMessagesPopup extends JFrame {

	SortedSet<MessageItem> messages;
	IBL BL;
	GUI gui;
    List<DrawData> drawDataList;

	public ViewPrivateMessagesPopup(final GUI gui, IBL BL, SortedSet<MessageItem> messages) {
		this.BL = BL;
		this.gui = gui;
        gui.setEnabled(false);
        gui.setIsEnabled(false);
		this.messages = messages;
		this.setAlwaysOnTop(true);
		this.setTitle("View Private Messages");
		this.setIconImage(new ImageIcon(getClass().getResource("resources/windowIcon.gif")).getImage());
		
        this.addWindowListener(new WindowAdapter() {
        	public void windowClosing(java.awt.event.WindowEvent e) {
                gui.setIsEnabled(true);
                gui.setEnabled(true);
        	}
        });

		JScrollPane jScrollPane1 = new JScrollPane();
		JPanel mainPanel = new JPanel();
		jScrollPane1.setViewportView(mainPanel);

		this.add(jScrollPane1);

		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		this.setSize(510, 450);
		this.setBackground(Color.white);

		GridBagLayout gridLayout = new GridBagLayout();
		mainPanel.setLayout(gridLayout);
        mainPanel.setBackground(new Color(252, 251, 251));

		GridBagConstraints cons = new GridBagConstraints();
		cons.fill = GridBagConstraints.HORIZONTAL;
		cons.anchor = GridBagConstraints.NORTH;
		cons.insets = new Insets(20, 20, 0, 0);
		int wallCount = 0;
		
        drawDataList = new LinkedList<DrawData>();

		if (!messages.isEmpty()) {
			for (final MessageItem item : messages) {
				JLabel friendImageLabel = getFriendLabel(item.getSender());

				cons.gridx = 0;
				cons.gridy = wallCount;
				cons.gridheight = 3;
				cons.gridwidth = 1;
				cons.insets = new Insets(20, 20, 0, 0);
				mainPanel.add(friendImageLabel, cons);

				JLabel nameLabel = new JLabel(item.getSender().getName()
						.toUpperCase());
				nameLabel.setFont(new Font("Tahoma", Font.BOLD, 11));
				cons.gridx = 1;
				cons.gridy = wallCount;
				cons.gridheight = 1;
				cons.weightx = 1.0;
				cons.insets = new Insets(20, 20, 0, 10);
				mainPanel.add(nameLabel, cons);

				JTextArea wallText = new JTextArea(item.getMessage());
				wallText.setLineWrap(true);
				wallText.setWrapStyleWord(true);
				wallText.setEditable(false);
				wallText.setFont(new Font("Tahoma", Font.PLAIN, 11));
				cons.gridx = 1;
				cons.gridy = wallCount + 1;
				cons.gridheight = 1;
				cons.gridwidth = 3;
				cons.weightx = 1.0;
				cons.insets = new Insets(10, 20, 0, 10);
				mainPanel.add(wallText, cons);

				JLabel wallDate = new JLabel(item.getDate().toString());
				wallDate.setForeground(Color.GRAY);
				cons.gridx = 1;
				cons.gridy = wallCount + 2;
				cons.weightx = 0;
				cons.gridwidth = 1;
				cons.insets = new Insets(20, 20, 0, 0);
				mainPanel.add(wallDate, cons);

				final JButton deleteButton = new JButton("Delete Message");
				cons.gridx = 2;
				cons.gridy = wallCount + 2;
				cons.weightx = 0;
				cons.insets = new Insets(20, 20, 0, 5);
				mainPanel.add(deleteButton, cons);

				deleteButton
						.addMouseListener(new java.awt.event.MouseAdapter() {
							public void mouseClicked(
									java.awt.event.MouseEvent evt) {
								if (deleteButton.isEnabled())
								{
									deleteMessageButtonClicked(evt, item, deleteButton);
								}
							}
						});
				
				JButton replyButton = new JButton("Reply");
				cons.gridx = 3;
				cons.gridy = wallCount + 2;
				cons.insets = new Insets(20, 20, 0, 20);
				mainPanel.add(replyButton, cons);

				replyButton
						.addMouseListener(new java.awt.event.MouseAdapter() {
							public void mouseClicked(
									java.awt.event.MouseEvent evt) {
								replyButtonButtonClicked(evt, item.getSender());
							}
						});

				if (messages.last() == item) {
					cons.weighty = 1.0;
				}

				JSeparator seperator = new JSeparator();
				cons.gridx = 0;
				cons.gridy = wallCount + 3;
				cons.gridwidth = 4;
				cons.insets = new Insets(20, 20, 0, 20);
				mainPanel.add(seperator, cons);

				wallCount += 4;
			}
	        (new ImageLoader(drawDataList)).execute();
		}
	}
	
	private void deleteMessageButtonClicked(java.awt.event.MouseEvent evt, MessageItem item, JButton button)
	{
		this.setAlwaysOnTop(false);
		gui.deletePrivateMessage(item, button);
		this.setAlwaysOnTop(true);
	}
	
	private void replyButtonButtonClicked(java.awt.event.MouseEvent evt, ShortCharacterItem friend)
	{
		this.setAlwaysOnTop(false);
		PrivateMessagePopup popup = new PrivateMessagePopup(friend, gui);
		popup.setVisible(true);
		
		popup.addWindowListener(new WindowAdapter() {
        	public void windowClosed(java.awt.event.WindowEvent e) {
                gui.setIsEnabled(false);
                gui.setEnabled(false);
        	}
        });
	}

	public JLabel getFriendLabel(final ShortCharacterItem friend) {
		JLabel friendImageLabel = new javax.swing.JLabel();
		friendImageLabel.setBorder(javax.swing.BorderFactory
				.createLineBorder(new java.awt.Color(0, 0, 0)));
		friendImageLabel.setPreferredSize(new java.awt.Dimension(50, 50));
		friendImageLabel.setName("friendLabel" + friend.getId());
		
        friendImageLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        friendImageLabel.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
            	ViewPrivateMessagesPopup.this.setAlwaysOnTop(false);
        		int dialogResponse = JOptionPane.showConfirmDialog(null,
        				"Are you sure you want to view " + friend.getName()
        						+ "'s profile?", "Change View",
        				JOptionPane.YES_NO_OPTION);
        		if (dialogResponse == 0) {
                    ViewPrivateMessagesPopup.this.setVisible(false);
                    ViewPrivateMessagesPopup.this.dispose();
                    gui.setEnabled(true);
                    gui.setIsEnabled(true);
                    gui.requestFocus();
        			gui.getCharacterForView(friend);
        		}
            	ViewPrivateMessagesPopup.this.setAlwaysOnTop(true);
            }
        });
        
		java.net.URL imgURL = null;

		if (friend.getProfileImage() == null) {
			imgURL = getClass()
					.getResource("resources/defaultProfileImage.jpg");
		} else {
			try {
				imgURL = new java.net.URL(friend.getProfileImage().getLink());
			} catch (MalformedURLException e) {
				imgURL = getClass().getResource(
						"resources/defaultProfileImage.jpg");
			}
		}

		DrawData drawData = new DrawData(friendImageLabel, imgURL, 50, 50);
		drawDataList.add(drawData);

		return friendImageLabel;
	}
	
	public void showMessageSentSuccessfullyMessage(String message)
	{
		JOptionPane.showMessageDialog(null, message, "Operation Successful", JOptionPane.INFORMATION_MESSAGE);
		ViewPrivateMessagesPopup.this.setAlwaysOnTop(true);
	}
}
